/**********************************************************************************************************************
 *
 * Project:    mGameEngine
 * File:       wavloader.cpp
 * Author:     karooolek
 * Created on: 2009-03-24
 *
 **********************************************************************************************************************/

#include "wavloader.h"

namespace mGameEngine
{
namespace Audio
{

WAVLoader::WAVLoader() :
    SoundLoader()
{
}

WAVLoader::WAVLoader(const String &filename) :
    SoundLoader(filename)
{
}

WAVLoader::~WAVLoader()
{
}

void WAVLoader::load()
{
    // begin sound loading
    _state = 0.0f;

    // delete old sound
    if(_sound)
    {
        delete _sound;
        _sound = NULL;
    }

    // open file for reading in binary mode
    FILE *fp = fopen(_filename, "rb");
    if(!fp)
    {
        return;
    }

    // read WAV header
    WAVHeader header;
    fread(&header, 1, sizeof(WAVHeader), fp);

    // invalid header or version
    if(strncmp(header.id, "RIFF", 4) != 0 || strncmp(header.format, "WAVE", 4) != 0)
    {
        return;
    }

    // read data
    uint size = header.dataSize;
    uint8 *data = new uint8[size];
    if(!data)
    {
        return;
    }
    fread(data, 1, size, fp);

    uint8 channels = header.nChannels;
    uint8 bps = header.bitsPerSample;
    uint length = size / bps * 8 / channels;
    uint sampleRate = header.sampleRate;

    // create sound
    _sound = new Sound(data, length, sampleRate, channels, bps);

    // close file
    fclose(fp);
    delete[] data;

    // sound is loaded
    _state = 1.0f;
}

}
}

